package com.yisu.es;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yisu.es.executor.EsQueryExecutor;
import com.yisu.es.model.EsQueries;
import com.yisu.es.parser.EsQueryParser;
import com.yisu.es.resp.DocUser;
import com.yisu.es.resp.ElasticsearchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Properties;

/**
 * @author xuyisu
 */
public class ElasticsearchQuery {

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchQuery.class);

    public static void main(String[] args) {
        try {
            Properties properties = loadProperties();
            String queryFilePath = properties.getProperty("es.query.file.path", "/mapper/es-queries.xml");
            String esUrl = properties.getProperty("es.url", "http://localhost:9200/tel_user/_search");

            EsQueries esQueries = EsQueryParser.parse(queryFilePath);
            EsQueryExecutor executor = new EsQueryExecutor(esQueries);
            URL url = new URL(esUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            // 设置连接超时时间为5秒
            conn.setConnectTimeout(5000);
            // 设置读取超时时间为5秒
            conn.setReadTimeout(5000);

            // 定义Elasticsearch DSL查询
            String dslQuery = executor.executeQuery("findByName", new HashMap<>(), "tel_user");

            // 发送DSL查询
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = dslQuery.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应
            int code = conn.getResponseCode();
            if (code == 200) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println(response);
                    String jsonResponse = response.toString();
                    ObjectMapper objectMapper = new ObjectMapper();
                    ElasticsearchResponse<DocUser> esResponse = objectMapper.readValue(jsonResponse, objectMapper.getTypeFactory().constructParametricType(ElasticsearchResponse.class, DocUser.class));
                    logger.info("Elasticsearch response: {}", JSONUtil.toJsonStr(esResponse));
                }
            } else {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String errorLine;
                    while ((errorLine = br.readLine()) != null) {
                        errorResponse.append(errorLine.trim());
                    }
                    logger.error("Error response from Elasticsearch: {}", errorResponse.toString());
                    System.out.println("Error: " + code);
                }
            }

        } catch (Exception e) {
            logger.error("An error occurred while executing Elasticsearch query", e);
        }
    }

    private static Properties loadProperties() {
        Properties properties = new Properties();
        try (InputStream inputStream = ElasticsearchQuery.class.getClassLoader().getResourceAsStream("application.properties")) {
            if (inputStream != null) {
                properties.load(inputStream);
            }
        } catch (IOException e) {
            logger.warn("Failed to load properties file", e);
        }
        return properties;
    }
}
